<script>
import apis from '../../apis/jind';
import RulePopup from '../rule-popup';
import LoginPopup from '../login-popup';
import LoginForm from '@/components/login-form';
import countTo from 'vue-count-to';
import ActiveDesc from '@/components/active-desc';
import { Toast } from 'vant';

const urlMap = {
  ydh: {
    name: '云订货',
    activityType: 1,
    productTypeId: 0,
    url: ''
  },
  ycm: {
    // 暂时先用着
    name: '云财贸',
    activityType: 0,
    productTypeId: 100842,
    url: 'https://vip1.jdy.com/app/dist/index.html#/home/index'
  },
  ykj: {
    name: '云会计',
    activityType: 2,
    productTypeId: 0,
    url: 'https://vip1.jdy.com/app/dist/index.html#/home/index'
  },
  yjxc: {
    name: '云进销存',
    activityType: 3,
    productTypeId: 0,
    url:
      'http://vip2.jdy.com/app/dist/index.html?dbid=791393489760&loginName=kingdeetestlite2016&realLoginName=&realName=&uid=0&isNew=false&hasComp=false&isAdmin=true&access_token=exWsuAAr0fCKVFNE*6JRA9uRjpGypxZkHxqKUiToHkfCsIVJ-HXvulgxzOXuqO49s8QI6Afk-42l6sC3u*JDDTSumFgq9CzQGRtYIkIijoirhHA5Z3Y7VUYCTzYuPkHa&isDebug=null#/home/index'
  },
  jdyv5: {
    name: '精斗云v5',
    activityType: 0,
    productTypeId: 100972,
    url: ''
  },
  ypt: {
    name: '云票通',
    activityType: 0,
    productTypeId: 221,
    url: ''
  },
  xrxs: {
    name: '薪人薪事',
    activityType: 0,
    productTypeId: 300,
    url: ''
  },
  wsc: {
    name: '小程序商城',
    activityType: 0,
    productTypeId: 220,
    url: ''
  },
  fxxk: {
    name: '纷享销客',
    activityType: 0,
    productTypeId: 222,
    url: ''
  },
  e1688: {
    name: '精斗云1688版E经经',
    activityType: 0,
    productTypeId: 101072,
    url: ''
  },
  mjdy: {
    name: '移动首页',
    activityType: 0,
    productTypeId: 101253,
    url: ''
  }
};

export default {
  components: {
    RulePopup,
    LoginForm,
    LoginPopup,
    ActiveDesc,
    countTo
  },
  data() {
    return {
      urlMap,
      tel: '13530821390',
      code: '',
      checked: true,
      jzParams: null,
      checkInfo: null,
      showLoginPop: false,
      showRulePop: false,
      loginAfterUrl: '',
      startNum: 0,
      endNum: 1000000,
      numDuration: 3000,
      orgUrl: 'https://m.jdy.com',
      swiperOptions: {
        initialSlide: 0
      }
    };
  },
  computed: {
    disabled() {
      return this.tel.length !== 11 || !this.checked || !this.code.length;
    }
  },
  mounted() {
    this.doGeetestChallenge();
  },
  methods: {
    handleLook(url) {
      this.loginAfterUrl = url;
      this.showLoginPop = true;
    },
    handleLookPop() {
      this.loginAfterUrl = '';
      this.showLoginPop = true;
    },
    deteckEnv() {
      const fn = () => {
        const isMobile = /Android|webOS|iPhone|iPod|BlackBerry/i.test(
          navigator.userAgent
        );
        if (isMobile) {
          this.$router.replace('/');
        } else {
          this.$router.replace('/pc-home');
        }
      };
      fn();
      setInterval(fn, 1500);
    },

    showToast(str) {
      const isMobile = /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent);
      if (isMobile) {
        Toast(str);
      } else {
        Toast(str);
      }
    },

    // 初始化极验信息
    doGeetestChallenge() {
      const _this = this;
      apis
        .geetestChallenge()
        .then(res => {
          if (+res.success === 1) {
            this.checkInfo = res;
            const callback = () => {
              this.$initGeet(
                {
                  gt: res.gt,
                  challenge: res.challenge,
                  offline: !res.success,
                  new_captcha: true,
                  product: 'bind'
                },
                function(captchaObj) {
                  window.gt = captchaObj;
                  captchaObj
                    .onReady(function() {})
                    .onSuccess(function() {
                      _this.jzParams = captchaObj.getValidate();
                    })
                    .onError(function(err) {
                      console.log(err);
                    });
                }
              );
            };
            callback();
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    // 点击获取验证码
    handleGetCode({ tel, success }) {
      this.tel = tel;
      const callback = () => {
        if (!this.jzParams) {
          window.gt.verify();
          this.$watch('jzParams', val => {
            console.log(val);
            if (val) {
              this.doGetCode(success);
            }
          });
        } else {
          this.doGetCode(success);
        }
      };
      this.checkMobile(callback);
    },

    // 点击注册
    handleLogin(form) {
      const _this = this;
      Toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true, // 禁用背景点击
        // loadingType: 'spinner',
        message: '请耐心等候...'
      });
      apis
        .registerForJdy({
          mobile: form.tel,
          vcode: form.code
        })
        .then(res => {
          if (!res.data) {
            Toast.clear();
            return this.showToast(res.msg, 'error');
          }
          window.pushRegNotice(); // 发送注册成功的通知
          setTimeout(() => {
            Toast.clear();
            if (_this.showLoginPop) {
              if (_this.loginAfterUrl) {
                window.location.href = _this.loginAfterUrl;
              } else {
                _this.showLoginPop = false;
                setTimeout(() => {
                  _this.$alert('您已成功申请免费体验，我们会尽快联系您', '提示', {
                    confirmButtonText: '确定',
                    callback: action => {
                      window.location.href = _this.orgUrl;
                    }
                  });
                }, 500);
              }
            } else {
              window.location.href = _this.orgUrl;
            }
            _this.showLoginPop = false;
          }, 1500);
        })
        .catch(_ => {
          Toast.clear();
          this.showToast('登录失败', 'error');
        });
    },

    // 校验手机号是否存在
    checkMobile(callback) {
      apis
        .checkMobileYZJAndJDYForRegister({
          mobile: this.tel
        })
        .then(res => {
          if (res.result === 1) {
            this.showToast('手机号已注册', 'error');
          } else {
            callback && callback();
          }
        })
        .catch(error => {
          if (error && error.toString) {
            error = error.toString;
          }
          this.showToast(`请求失败${error}`, 'error');
        });
    },

    // 获取验证码
    doGetCode(success) {
      /* eslint-disable */
      apis
        .geetestVerify({
          mobile: this.tel,
          geetest_challenge: this.jzParams.geetest_challenge,
          geetest_validate: this.jzParams.geetest_validate,
          geetest_seccode: this.jzParams.geetest_seccode,
          sessionId: this.checkInfo.sessionId
        })
        .then(res => {
          if (!res.result) {
            this.showToast('操作过于频繁，请稍后再试', 'error');
          } else if (res.result.status === 'failed') {
            this.showToast(res.result.desc, 'error');
          } else {
            this.jzParams = null;
            success && success();
            this.showToast('短信发送成功', 'success');
          }
        })
        .catch(_ => {
          this.showToast('发送短信失败', 'error');
        });
    }
  }
};
</script>